package com.hmall.search.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.apache.commons.lang.StringUtils;

import org.apache.lucene.index.Terms;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchService implements ISearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private  static  final ObjectMapper MAPPER= new ObjectMapper();

    @Override
    public List<String> getSuggestion(String prefix) throws IOException {
        SearchRequest request = new SearchRequest("item");
        request.source().fetchSource(new String[0],null);
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "my_suggestion", SuggestBuilders.completionSuggestion("suggestion")
                        .size(10)
                        .skipDuplicates(true)
                        .prefix(prefix)
        ));
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        CompletionSuggestion suggestion = search.getSuggest().getSuggestion("my_suggestion");
        List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            list.add(option.getText().string());
        }
        return list;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) throws IOException {
        SearchRequest request = new SearchRequest("item");
        request.source().size(0);
        buildBasicQuer(request,params);
        request.source().aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(20)
        );
        request.source().aggregation(
                AggregationBuilders.terms("category").field("category").size(20)
        );
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        Map<String,List<String>>map = new HashMap<>(2);
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get("brandAgg");

        List<String> brandList = new ArrayList<>();
        return null;
    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) throws Exception {
        SearchRequest request = new SearchRequest("item");
        buildBasicQuer(request,params);
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1)*size).size(size);

        String sortBy = params.getSortBy();
        if ("sold".equals(sortBy)){
            request.source().sort(sortBy, SortOrder.DESC);
        }else if ("price".equals(sortBy)){
            request.source().sort(sortBy, SortOrder.ASC);
        }
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        SearchHit[] hits1 = hits.getHits();
        List<ItemDoc> list = new ArrayList<>(hits1.length);
        for (SearchHit documentFields : hits1) {
            String sourceAsString = documentFields.getSourceAsString();
            ItemDoc itemDoc = MAPPER.readValue(sourceAsString,ItemDoc.class);
            Map<String, HighlightField> map = documentFields.getHighlightFields();
            if (map !=null&& map.size()>0){
                HighlightField field = map.get("name");
                String string = field.getFragments()[0].string();
                itemDoc.setName(string);
            }
            list.add(itemDoc);
        }
        return new PageDTO<>(value,list);
    }

    private void buildBasicQuer(SearchRequest request, RequestParams params) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)){
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)){
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)){
            boolQuery.filter(QueryBuilders.termQuery("category",category));
        }
        Long minPrice  = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (maxPrice != null && maxPrice !=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice *100).lte(maxPrice *100));
        }
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );
        request.source().query(boolQuery);
    }
}
